﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 在线用户
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20
    /// </summary>
    public class UserOnlineBll
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserOnlineModel>> GetList()
        {
            try
            {
                var tenantId = TenantProvider.GetTenant.TenantId;
                var userOnlineList = new List<UserOnlineModel>();
                var onlineUserKey = CacheKey.LOGINONLINE;
                var keys = CacheFactory.Cache.GetAllKeys();
                if (!string.IsNullOrEmpty(tenantId))
                    keys = keys.FindAll(q => q.Contains(tenantId));
                foreach (var cacheKey in keys)
                {
                    if (cacheKey.Length > onlineUserKey.Length && cacheKey.Substring(0, onlineUserKey.Length) == onlineUserKey)
                    {
                        var onlineToken = CacheFactory.Cache.Get(cacheKey);
                        var userInfo = CacheFactory.Cache.Get<UserInfo>(onlineToken);
                        if (userInfo != null)
                        {
                            userOnlineList.Add(new UserOnlineModel
                            {
                                userId = userInfo.UserId,
                                userAccount = userInfo.UserAccount,
                                userName = userInfo.UserName + "/" + userInfo.UserAccount,
                                loginIPAddress = userInfo.LoginIPAddress,
                                loginTime = userInfo.LoginTime.ToString(),
                                loginPlatForm = userInfo.LoginPlatForm,
                                tenantId = userInfo.TenantId
                            });
                        }
                    }
                }
                return userOnlineList.OrderByDescending(o => o.loginTime).ToList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        public async Task Delete(string id)
        {
            try
            {
                UserProvider.Instance.RemoveOnLine(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
    }
}
